<template>
    <div class="article-container">
        <!-- 导航栏 -->
        <van-nav-bar class="page-nav-bar" left-arrow title="AC博客" @click-left="router.back()"></van-nav-bar>
        <!-- /导航栏 -->

        <div class="main-wrap">
            <!-- 加载中 -->
            <div v-if="loading" class="loading-wrap">
                <van-loading color="#3296fa" vertical>加载中</van-loading>
            </div>
            <!-- /加载中 -->

            <!-- 加载完成-文章详情 -->
            <div v-else-if="dataList.aticleData.title" class="article-detail">
                <!-- 文章标题 -->
                <h1 class="article-title">{{ dataList.aticleData.title }}</h1>
                <!-- /文章标题 -->

                <!-- 用户信息 -->
                <van-cell class="user-info" center :border="false">
                    <template #icon>
                        <van-image center class="avatar" round fit="cover" :src="dataList.aticleData.aut_photo" />
                    </template>
                    <template #title>
                        <div class="user-name">{{ dataList.aticleData.aut_name }}</div>
                    </template>
                    <template #label>
                        <div class="publish-date">{{ dayJS().to(dayJS(dataList.aticleData.pubdate)) }}</div>
                    </template>

                    <!-- 组件按钮 -->
                    <!-- $event表示事件参数 -->
                    <follow-btn @up_is_followed="dataList.aticleData.is_followed = $event"
                        :userId="dataList.aticleData.aut_id" :isFollowed="dataList.aticleData.is_followed">
                    </follow-btn>
                    <!-- 当我们给子组件的数据既要被使用 还需要被修改，可用用v-model来简化写法 -->
                    <!-- <follow-btn
                    :userId="dataList.aticleData.aut_id"
                    v-model="dataList.aticleData.is_followed">
                    </follow-btn> -->

                </van-cell>
                <!-- /用户信息 -->

                <!-- 文章内容 -->
                <div v-html="dataList.aticleData.content" class="article-content markdown-body" ref="articleContent">
                </div>
                <van-divider>正文结束</van-divider>
                <!-- 文字评论区 -->
                <comment-list @reply-click="onReplyClick" @onload-success="onloadSuccess"
                    :source="dataList.aticleData.art_id" :list="commentList"></comment-list>
                <!-- 文字评论区 -->
                <!-- 底部区域 -->
                <div class="article-bottom">
                    <van-button class="comment-btn" type="default" round @click="isPospShow = true"
                        size="small">写评论</van-button>
                    <van-icon name="comment-o" :badge="tatalCommentCount" color="#777" />
                    <!-- 收藏组件 -->
                    <collect-artcle @up_is_collected="dataList.aticleData.is_collected = $event"
                        :aticleId="dataList.aticleData.art_id"
                        :isCollected="dataList.aticleData.is_collected"></collect-artcle>
                    <!-- 点赞组件 -->
                    <like-aticle @up_attitude="dataList.aticleData.attitude = $event"
                        :isLike="dataList.aticleData.attitude" :aticleId="dataList.aticleData.art_id" />
                    <van-icon name="share" color="#777777"></van-icon>
                </div>
                <!-- /底部区域 -->
                <!-- 发布评论 -->
                <van-popup v-model:show="isPospShow" position="bottom">
                    <comment-post @psot-success="onPostSuccess" :target="dataList.aticleData.art_id">

                    </comment-post>
                </van-popup>
            </div>
            <!-- /加载完成-文章详情 -->

            <!-- 加载失败：404 -->
            <div v-else-if="errStatus === 404" class="error-wrap">
                <van-icon name="failure" />
                <p class="text">该资源不存在或已删除！</p>
            </div>
            <!-- /加载失败：404 -->

            <!-- 加载失败：其它未知错误（例如网络原因或服务端异常） -->
            <div v-else class="error-wrap">
                <van-icon name="failure" />
                <p class="text">内容加载失败！</p>
                <van-button @click="getAticleById" class="retry-btn">点击重试</van-button>
            </div>
            <!-- /加载失败：其它未知错误（例如网络原因或服务端异常） -->
        </div>
        <!--评论回复-->
        <!-- 弹层是懒渲染 -->
        <van-popup v-if="isReplyShow" v-model:show="isReplyShow" position="bottom" style="height:93%">
            <comment-reply @upReply_count="currentComment.reply_count++" @upCommentPraise="upCommentPraise" @close="isReplyShow = false" :comment="currentComment"></comment-reply>
        </van-popup>
    </div>
</template>

<script>
import { getAticleByIdAPI } from '@/api/article'
import { reactive, inject, ref, onMounted, provide } from 'vue'
import { useRouter } from 'vue-router'
import { ImagePreview } from 'vant'
import collectArtcle from '@/components/collect-artcle/collectArtcle.vue'
import followBtn from '@/components/follow-btn/followBtn.vue'
import likeAticle from '@/components/like-aticle/likeAticle.vue'
import commentList from './components/commentList.vue'
import commentPost from './components/commentPost.vue'
import commentReply from './components/commentReply.vue'
export default {
  name: 'Aticle',
  props: {
    aticleId: {
      type: [Number, String, Object],
      required: true
    }
  },
  components: {
    followBtn,
    collectArtcle,
    likeAticle,
    commentList,
    commentPost,
    commentReply
  },
  setup (props) {
    const dataList = reactive({
      aticleData: {}
    })
    const dayJS = inject('dayJS')
    const router = useRouter()
    const loading = ref(true)
    const articleContent = ref(null)
    const followLoading = ref(false)
    const tatalCommentCount = ref(0)
    const isPospShow = ref(false)
    const commentList = ref([])
    const isReplyShow = ref(false)
    const currentComment = ref({})// 点击回复的评论对象
    // 依赖注入
    provide('articleId', props.aticleId)
    // 失败的状态码
    const errStatus = ref(0)
    // 点击图片预览
    const previewImage = () => {
      const imgs = articleContent.value.querySelectorAll('img')
      const images = []
      imgs.forEach((img, index) => {
        images.push(img.src)
        img.onclick = () => {
          console.log(img)
          ImagePreview({
            images: images,
            startPosition: index
          })
        }
      })
    }
    //
    const onloadSuccess = (data) => {
      tatalCommentCount.value = data.total_count
      const { results } = data
      commentList.value.push(...results)
    }
    //
    const onReplyClick = (comment) => {
      // console.log(comment)
      currentComment.value = comment
      isReplyShow.value = true
    }
    //
    const upCommentPraise = (data) => {
      data === 1 ? currentComment.value.like_count-- : currentComment.value.like_count++
      currentComment.value.is_liking = !currentComment.value.is_liking
    }
    //
    const onPostSuccess = (data) => {
      isPospShow.value = false
      commentList.value.unshift(data.new_obj)
      tatalCommentCount.value++
    }
    // 加载文章详情
    const getAticleById = async () => {
      loading.value = true
      try {
        const { data } = await getAticleByIdAPI(props.aticleId)
        dataList.aticleData = data.data
        setTimeout(() => {
          previewImage()
        }, 10)
      } catch (err) {
        if (err.response && err.response.status === 404) {
          errStatus.value = 404
        }
        console.log(err)
      }
      // 请求完成 关闭loading
      loading.value = false
    }
    onMounted(() => {
      getAticleById()
    })

    return {
      dataList,
      dayJS,
      router,
      loading,
      errStatus,
      getAticleById,
      articleContent,
      followLoading,
      tatalCommentCount,
      isPospShow,
      onPostSuccess,
      commentList,
      isReplyShow,
      onReplyClick,
      currentComment,
      onloadSuccess,
      upCommentPraise
    }
  }
}
</script>

<style scoped lang="less">
// 文章正文样式
@import "./github-markdown.css";

.article-container {
    .main-wrap {
        position: fixed;
        left: 0;
        right: 0;
        top: 92px;
        bottom: 88px;
        overflow-y: scroll;
        background-color: #fff;
    }

    .article-detail {
        .article-title {
            font-size: 40px;
            padding: 50px 32px;
            margin: 0;
            color: #3a3a3a;
        }

        .user-info {
            padding: 0 32px;

            :deep(.van-cell__value--alone) {
                display: flex;
                justify-content: space-between;
                align-items: center;
            }

            .rightAll {
                display: flex;
                align-items: center;
            }

            .avatar {
                width: 70px;
                height: 70px;
                margin-right: 17px;
            }

            .van-cell__label {
                margin-top: 0;
            }

            .user-name {
                font-size: 24px;
                color: #3a3a3a;
            }

            .publish-date {
                font-size: 23px;
                color: #b7b7b7;
            }
        }

        .article-content {
            padding: 55px 32px;

            :deep(p) {
                text-align: justify;
            }
        }
    }

    .loading-wrap {
        padding: 200px 32px;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #fff;
    }

    .error-wrap {
        padding: 200px 32px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        background-color: #fff;

        .van-icon {
            font-size: 122px;
            color: #b4b4b4;
        }

        .text {
            font-size: 30px;
            color: #666666;
            margin: 33px 0 46px;
        }

        .retry-btn {
            width: 280px;
            height: 70px;
            line-height: 70px;
            border: 1px solid #c3c3c3;
            font-size: 30px;
            color: #666666;
        }
    }

    .article-bottom {
        position: fixed;
        left: 0;
        right: 0;
        bottom: 0;
        display: flex;
        justify-content: space-around;
        align-items: center;
        box-sizing: border-box;
        height: 88px;
        border-top: 1px solid #d8d8d8;
        background-color: #fff;

        .comment-btn {
            width: 282px;
            height: 46px;
            border: 2px solid #eeeeee;
            font-size: 30px;
            line-height: 46px;
            color: #a7a7a7;
        }

        .van-icon {
            font-size: 40px;

            .van-info {
                font-size: 16px;
                background-color: #e22829;
            }
        }
    }
}
</style>
